package com.elot.core.security;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.elot.dto.UserDto;
import com.elot.service.UserService;

@Component("jdoUserDetailsService")
public class JdoUserDetailsService implements UserDetailsService{

	@Autowired
	UserService userService;
	
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
		
		if (userName==null || "".equals(userName)) {
			throw new BadCredentialsException("Username may not be empty");
		}
		
		UserDto user;
		
		try {
			user = userService.findByName(userName);
		} catch (Exception e) {
			throw new DataRetrievalFailureException("Problem retrieving user from database", e);
		}
		
		if (user == null) {
			throw new UsernameNotFoundException("User for username '"+userName+"' not found in database. Authentication failed.");
		}
		
		if (user.getRole() == null) {
			throw new UsernameNotFoundException("User needs to have at least one granted authority");
		}
		
		Collection<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
		grantedAuthorities.add(new GrantedAuthorityImpl(user.getRole().name()));
		
		return new User(user.getUser(), user.getPassword(), true, true, true, true, grantedAuthorities);

	}
	
	
	
	

}
